import axios from 'axios'
import { useUserStore } from '../store/user'
import { useRouter } from 'vue-router'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 刷新token的函数
const refreshToken = async () => {
  try {
    const refreshToken = localStorage.getItem('refreshToken')
    if (!refreshToken) return null

    const response = await axios.post('/refresh', {}, {
      headers: { 'Authorization': `Bearer ${refreshToken}` }
    })

    const { accessToken } = response.data
    localStorage.setItem('token', accessToken)
    return accessToken
  } catch (error) {
    console.error('刷新token失败:', error)
    return null
  }
}

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 200) {
      return res.data
    }
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  async error => {
    const router = useRouter()
    const userStore = useUserStore()

    if (error.response) {
      const { status } = error.response
      
      // 处理401未授权错误
      if (status === 401) {
        // 尝试刷新token
        const newToken = await refreshToken()
        if (newToken) {
          // 重试原请求
          error.config.headers.Authorization = `Bearer ${newToken}`
          return request(error.config)
        } else {
          // 刷新token失败，清除用户信息并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('refreshToken')
          userStore.logout()
          router.push('/login')
        }
      }
      
      // 处理其他错误
      switch (status) {
        case 400:
          error.message = '请求错误'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = '请求地址不存在'
          break
        case 429:
          error.message = '请求过于频繁，请稍后再试'
          break
        default:
          error.message = '服务器错误'
      }
    } else {
      error.message = '网络连接失败'
    }

    // 打印错误日志
    console.error('Response error:', {
      url: error.config?.url,
      status: error.response?.status,
      data: error.response?.data,
      message: error.message
    })
    
    return Promise.reject(error)
  }
)

export default request